<template>
  <el-row type="flex" justify="center" align="middle" class="wrapper">
    <el-form ref="form" :model="form" label-width="50px">
      <el-form-item label="账号">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="form.password" type="password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-row>
</template>

<script>
export default {
  data() {
    return {
      form: {
        username: "",
        password: ""
      }
    };
  },
  methods: {
    onSubmit() {
      //   console.log(this.form);
      this.$axios({
        url: "/login",
        method: "POST",
        // data: {
        //   username: this.form.username,
        //   password: this.form.password
        // }
        data: this.form
      }).then(res => {
        if (!this.form.username || !this.form.password) {
          return this.$message.error("用户名和密码不能为空");
        }
        console.log(res.data);
        const { data, message } = res.data;
        if (message == "登录成功") {
          localStorage.setItem("token", data.token);
          localStorage.setItem("user", JSON.stringify(data.user));
          this.$message({
            message: "登录成功",
            type: "success"
          });
          setTimeout(() => {
            this.$router.push("/");
          }, 800);
        } else {
          this.$message.error("用户名和密码错误");
          //清空输入框
          this.form = {};
        }
      });
    },
    reset() {
      this.form = {
        username: "",
        password: ""
      };
    }
  }
};
</script>

<style lang="less" scoped>
.wrapper {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
  background-color: #f2f2f2;
  .el-form {
    background-color: #fefefe;
    padding: 10px;
    width: 360px;
  }
}
</style>